package repository

import (
	"fmt"
	"log"
	"net/url"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
)

var DB *gorm.DB

// 初始化数据库
func InitDB() *gorm.DB {
	// 数据库信息
	driverName := viper.GetString("db_datasource.driverName")
	host := viper.GetString("db_datasource.host")
	port := viper.GetString("db_datasource.port")
	database := viper.GetString("db_datasource.database")
	username := viper.GetString("db_datasource.username")
	password := viper.GetString("db_datasource.password")
	charset := viper.GetString("db_datasource.charset")
	loc := viper.GetString("db_datasource.loc")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true&loc=%s",
		username,
		password,
		host,
		port,
		database,
		charset,
		url.QueryEscape(loc))
	fmt.Printf(args)

	// 打开数据库
	db, err := gorm.Open(driverName, args)
	if err != nil {
		log.Printf("fail to connect database, err: %v", err.Error())
		panic("fail to connect database, err: " + err.Error())
	}

	// 四地服务数据，分表
	DB = db
	return db
}

// 拿数据库
func GetDB() *gorm.DB {
	return DB
}
